const Koa = require('koa')
const app = new Koa();
const cron = require('node-cron');

const json = require('koa-json')
const onerror = require('koa-onerror')
const logger = require('koa-logger')
const views = require('koa-views')
const {
  koaBody
} = require('koa-body');

const router = require('koa-router')();
const index = require('./routes/index')
const users = require('./routes/users');
const clazz = require('./routes/class');
const clazzType = require('./routes/class/type');

const commonService = require('./services/common/index');

// 在应用启动时创建定时任务
cron.schedule('* * * * *',async () => {
  const start = new Date();
  const result = await commonService.classStatus();
  console.log(result);
  const ms = new Date() - start;
  console.log(`定时任务执行完毕,耗时 ${ms} ms,时间 ${start}`);
});

// error handler
onerror(app)
// middlewares
app.use(koaBody({
  multipart: true, // 是否支持 multipart-formdate 的表单,是否支持多张上传
  stict: false, // 设为false // 默认true
}));
app.use(json())
app.use(logger())
app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))
app.use(require('koa-static')(__dirname + '/public'));
app.use(require('koa-static')(__dirname + '/public/template'));

// logger
app.use(async (ctx, next) => {
  // 设置允许的源
  ctx.set("Access-Control-Allow-Origin", "*");

  // 设置允许的请求头
  ctx.set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");

  // 设置允许的请求方法
  ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  // 处理预检请求
  if (ctx.method === 'OPTIONS') {
    ctx.status = 204;
    return;
  }
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})


// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(clazz.routes(), clazz.allowedMethods())
app.use(clazzType.routes(), clazzType.allowedMethods())
router.get('/*', (ctx, next) => {
  ctx.body = '404'
})
app.use(router.routes(), router.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app;